import React from "react";
import { Modal, Form, Input, Select, message } from "antd";
import type { FormInstance } from "antd/es/form";

const { TextArea } = Input;

interface NewDiscussionProps {
  visible: boolean;
  onCancel: () => void;
  onSubmit: (values: {
    title: string;
    content: string;
    tags: string[];
  }) => void;
}

const commonTags = [
  "课程问题",
  "作业疑问",
  "学习方法",
  "资源分享",
  "考试相关",
  "其他",
];

const NewDiscussion: React.FC<NewDiscussionProps> = ({
  visible,
  onCancel,
  onSubmit,
}) => {
  const [form] = Form.useForm();

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      onSubmit(values);
      form.resetFields();
    } catch (error) {
      console.error("表单验证失败:", error);
    }
  };

  return (
    <Modal
      title="发起新讨论"
      open={visible}
      onCancel={onCancel}
      onOk={handleSubmit}
      okText="发布"
      cancelText="取消"
      destroyOnClose
    >
      <Form form={form} layout="vertical" initialValues={{ tags: [] }}>
        <Form.Item
          name="title"
          label="标题"
          rules={[
            { required: true, message: "请输入标题" },
            { max: 100, message: "标题最多100个字符" },
          ]}
        >
          <Input placeholder="请输入讨论标题" />
        </Form.Item>

        <Form.Item
          name="content"
          label="内容"
          rules={[
            { required: true, message: "请输入内容" },
            { max: 2000, message: "内容最多2000个字符" },
          ]}
        >
          <TextArea
            placeholder="请详细描述你的问题或想法..."
            autoSize={{ minRows: 4, maxRows: 8 }}
            showCount
            maxLength={2000}
          />
        </Form.Item>

        <Form.Item
          name="tags"
          label="标签"
          rules={[
            { required: true, message: "请至少选择一个标签" },
            { type: "array", max: 3, message: "最多选择3个标签" },
          ]}
        >
          <Select
            mode="multiple"
            placeholder="选择或输入标签"
            options={commonTags.map((tag) => ({ label: tag, value: tag }))}
            allowClear
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default NewDiscussion;
